<?php
define("MAPS_HOST", "maps.google.com");
define("KEY", "ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA");



class BusinessInfController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','login','register','business', 'activity', 'user'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * 商家登录
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionLogin()
	{
		$model = new Register();
		$model->unsetAttributes();  // clear any default values
//var_dump($_POST['LoginForm']);
		if(isset($_POST['Register']))
		{
		    $model->attributes=$_POST['Register'];		    
		}
//var_dump($model->login());
		$user = Register::model()->find('username=:username AND password=:password',
		    array(':username'=>$model->attributes['username'], 
		        ':password'=>$model->attributes['password']));
//var_dump($user);
		if($model->validate() && $user)
		{
		    //$this->redirect(Yii::app()->user->returnUrl);

		    //$this->redirect(array("./index.php?r=businessInf/business", 'post' => $post));
		    //$this->render('business', array('post' => $post));

		    $this->redirect(array('business', 'usr' => $model->username));
		}
		$this->render('login',array(
			'model'=>$model,
		));  
	    
	    
	}

	/**
	 * 商家注册
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionRegister()
	{
	    $model=new Register('search');
	    $model->unsetAttributes();  // clear any default values

	    if(isset($_POST['Register']))
	    {
	        $model->attributes=$_POST['Register'];
	    }

	 	$user = Register::model()->find('username=:username', 
	            array(':username'=>$model->attributes['username']));
	    //if($model->validate() && !$user)
	    if(isset($_POST['Register']) && $_POST['Register']['username'])
	    {
	        $model->save();
	        $this->redirect(array('login'));
	    }


	    $this->render('register',array(
	        'model'=>$model,
	    ));
	}
	
	/**
	 * 商家登录后的信息
	 */
	public function actionBusiness()
	{
//	    $model=new Register();
        $username = $_GET['usr'];
        /**根据获取到的用户名信息，在tbl_register数据库中查找用户名对应的其他数据*/
        $register_data= Register::model()->find('username=:username', array(':username'=>$username));
        
        /**根据获取到的用户名信息，在tbl_activity数据库中查找用户名对应的其他数据*/
        $model = new Activity();
        $activity_data= Activity::model()->findAll('username=:username', array(':username'=>$username));
        
	    $this->render('business',array(
	        'register_data'=>$register_data,
	        'activity_data'=>$activity_data,
	    ));
	}
	
	/**
	 * 创建活动信息
	 */
	public function actionActivity()
	{
		$model=new Activity('search');
	    $model->unsetAttributes();  // clear any default values

	    if(isset($_POST['Activity']))
	    {
	        $model->attributes=$_POST['Activity'];
	        /**获取活动地点经纬度*/
    		/* $location = $this->getLatLong($model->location);
    		$model->latitude = $location['latitude'];
    		$model->longitude = $location['longitude']; */
	        $model->latitude = 0;
	        $model->longitude = 0;
    		/**加载图片*/
    		$file = CUploadedFile::getInstance($model,'activityImg');
    		//var_dump($file);exit();
    		//判断实例化是否成功 将图片重命名
    		if(is_object($file)&&get_class($file) === 'CUploadedFile'){
    		    $model->activityImg = './images/file'.time().'_'.rand(0,9999).'.'.$file->extensionName;
    		}else{
    		    $model->activityImg = './images/test.jpg';
    		}
	    }

	    $username = $_GET['usr'];
	    $model->username = $username;
	     
	    
	    if($model->validate())
	    {
	        $model->save();
	        
	        if(is_object($file) && get_class($file) === 'CUploadedFile'){
        
	            $file->saveAs($model->activityImg, true);
	        } 
	        
	        $this->redirect(array('business', 'usr' => $username));
	    }

	    $this->render('activity',array(
	        'model'=>$model,
	    ));
	}
	
	/**
	 * 获取活动地址对应的经纬度
	 * @param unknown $address
	 */
	public function getLatLong($address){
	    //$address = "北京市朝阳区望花路西里";
        //$address = !emptyempty($_POST['address'])?$_POST['address']:"上海徐汇区漕宝70号";// Google HQ  
        $prepAddr = str_replace(' ','+',$address);  
        $context = stream_context_create(array(
            'http' => array(
                'timeout' => 10 //超时时间，单位为秒
            )
        ));
        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false',
                                    0, $context);  
        //var_dump($geocode);exit();
        $output= json_decode($geocode);  
          
        $location['latitude'] = $output->results[0]->geometry->location->lat;  
        $location['longitude'] = $output->results[0]->geometry->location->lng; 
        return $location;
    }

    
    /**
     * 接收用户数据
     */
    public function actionUser()
    {
        $model = new User();
         if(isset($_POST['User']))
         {
            $model->attributes = $_POST['User'];
            $model->longitude = $_POST['longitude'];
            $model->latitude = $_POST['latitude'];
            $model->save(); 
            $location['longitude'] = $_POST['longitude'];
            $location['latitude'] = $_POST['latitude'];
        }
    	else 
    	{
    	    $location['longitude'] = 114;
    	    $location['latitude'] = 41;    	    
    	}
        //$location['longitude'] = 100;
        //$location['latitude'] = 50;
    	
    	$activity = Activity::model()->findAll('end_time>:end_time', array(':end_time' => date('Y-m-d H:i:s',time())));
        
    	$activity_sort = $this->getActivity($activity, $location['longitude'], $location['latitude']);

    	$activity_sort[]['number'] = $this->activity_num;//向客户端发送活动总数量
    	echo json_encode($activity_sort);//向客户端发送各个活动信息
    
        //var_dump($_POST);
        //print ('111');
        //$test = $_POST
        //$this->render('login', array(
         //   'model' => $model,
       // ));
    }
    var $activity_num = 0;   //统计活动总数 
    
    /**
     * 获取排序好的活动记录
     * @param unknown $activity
     * @param unknown $longitude
     * @param unknown $latitude
     * @return Ambigous <number, multitype:NULL >
     */
    public function getActivity($activity, $longitude, $latitude)
    {
        $activity_new = array();
        /**从activity对象中取出对应的每条记录*/
        foreach ($activity as $value)
        {
            $activity_new[] = $value->attributes;
        }

        /**将数据库中的每条记录合并成一个二维数组*/
        foreach ($activity_new as $key => $value)
        {
            ++$this->activity_num;
            $activity_new[$key]['ditance'] = $this->getdistance($value['longitude'], $value['latitude'],
                $longitude, $latitude);
            /**把时间格式改为友好时间格式，采用date转换*/
            $start_time = strtotime($activity_new[$key]['start_time']);
            $end_time = strtotime($activity_new[$key]['end_time']);
            $end_time2 = $activity_new[$key]['end_time'];
            $activity_new[$key]['start_time'] = date("Y年m月d日H时i分s秒",$start_time);
            $activity_new[$key]['end_time'] = date("Y年m月d日H时i分s秒",$end_time);
            //var_dump($form_time);exit();
            //$diff_time = $end_time - strtotime(date('Y-m-d H:i:s',time()));
            //$diff_time = strtotime($end_time);
            //$tt = date("d日H时i分s秒",$diff_time);
           
            /**距离活动结束时间*/
            $activity_new[$key]['diff_time'] = $this->timediff(strtotime(date('Y-m-d H:i:s',time())), $end_time);
        } 
        $activity_sort = $this->my_sort($activity_new, 'ditance');
        return $activity_new;
    }
    
    
    /**
     *求两个已知经纬度之间的距离,单位为米
     *@param lng1,lng2 经度
     *@param lat1,lat2 纬度
     *@return float 距离，单位米
     *@author www.Alixixi.com
     **/
    function getdistance($lng1,$lat1,$lng2,$lat2){
        //将角度转为狐度
        $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2=deg2rad($lat2);
        $radLng1=deg2rad($lng1);
        $radLng2=deg2rad($lng2);
        $latMid=$radLat1-$radLat2;
        $lngMid=$radLng1-$radLng2;
        $distance=2*asin(sqrt(pow(sin($latMid/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($lngMid/2),2)))*6378.137;
        if($distance/1000 > 1)
        {
            $distance = round($distance/1000, 1).'Km';
            //$distance = $distance.'Km';
        }
        else 
        {
            $distance = round($distance, 2).'m';
        }
        
        return $distance;
    }    
	

    /**
     * 计算距离结束时间
     * @param unknown $start_time
     * @param unknown $end_time
     * @return string
     */
    function timediff($start_time,$end_time)
    {
        $timediff = $end_time-$start_time;
        $days = intval($timediff/86400);
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        $remain = $remain%3600;
        $mins = intval($remain/60);
        $secs = $remain%60;
        $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        if($res['day']){
            $diff_time = $res['day'].'天'.$res['hour'].'小时'.$res['min'].'分';
        }
        else if($res['hour'])
        {
            $diff_time = $res['hour'].'小时'.$res['min'].'分';
        }
        else if ($res['min'])
        {
            $diff_time = $res['min'].'分';
        }
/*         else if($res['sec'])
        {
            $diff_time = $res['sec'].'秒';
        }*/
        else 
        {
            $diff_time = '活动结束';
        } 
        return $diff_time;
    } 
    
    
    /**
     * 对数组进行排序
     * @param unknown $arrays
     * @param unknown $sort_key
     * @param string $sort_order
     * @param string $sort_type
     * @return boolean|unknown
     */
    function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        if(is_array($arrays) && isset($key_arrays)){

            array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        }
        return $arrays;
    }
    
    
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new BusinessInf;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BusinessInf']))
		{
			$model->attributes=$_POST['BusinessInf'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}


	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BusinessInf']))
		{
			$model->attributes=$_POST['BusinessInf'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('BusinessInf');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new BusinessInf('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['BusinessInf']))
			$model->attributes=$_GET['BusinessInf'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return BusinessInf the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=BusinessInf::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param BusinessInf $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='business-inf-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
